package com.fh.modules.kms.message;

import com.alibaba.fastjson.JSONObject;
import com.fh.modules.kms.entity.SqlLog;
import com.fh.modules.kms.service.SqlLogService;
import com.fh.modules.kms.vo.SqlLogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @Author qiujunda
 * @Date 22/06/2020
 * @Description
 */
@Component
public class RedisMessage implements MessageListener {
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
//    @Autowired
//    private SqlLogService sqlLogService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        taskExecutor.execute(() -> {
            RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
            String msg = serializer.deserialize(message.getBody());
            msg=msg.substring(msg.indexOf("{"));
            if(msg.startsWith("{{")){
                msg=msg.substring(msg.indexOf("{")+1);
            }
            try{
                SqlLogVo sqlLogVo=  JSONObject.parseObject(msg,SqlLogVo.class);
                String indexName=sqlLogVo.getIndexName();
                SqlLog sqlLog=sqlLogVo.getSqlLog();
                sqlLog.setId(System.currentTimeMillis());
                sqlLog.setDbName(indexName);
//                sqlLogService.save(sqlLog);
            }catch (Exception e){
                System.out.println(msg);
                e.printStackTrace();
            }

        });

    }

    public static void main(String[] args){
        String msg="{\"indexName\":\"fherptestlog\",\"sqlLog\":{\"actor\":\"deloitte\",\"logType\":\"查询\",\"requestBeginTime\":\"2020-06-22 21:21:38\",\"requestTime\":40,\"requestUrl\":\"/fhxherp//mgt/maintenance/qryBuyerStoreRelation.do\",\"sessionId\":\"fce44906-ee04-4546-991b-5feb1076d352\",\"clusterNode\":\"local\",\"sql\":\"12\"}}";
        System.out.println(msg);
        JSONObject json= (JSONObject) JSONObject.parse(msg);
        SqlLogVo sqlLogVo=  JSONObject.parseObject(msg,SqlLogVo.class);
        System.out.println("");
    }

}
